package com.lzy.websocket.websocket;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.lzy.websocket.bean.User;

/**
 * 握手拦截器
 * @author lzy
 *
 */
public class HandShakeInterceptor implements HandshakeInterceptor {

	/**
	 * 握手前执行的操作
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
		/* 从HttpSession中获取用户信息 */
		String username = ((User)servletRequest.getSession().getAttribute("user")).getUserName();
		/* 将HttpSession中的用户名信息拷入WebSocketSession中 */
		attributes.put("WEBSOCKET_USERNAME", username);
		return true;
	}

	/**
	 * 握手后执行的操作
	 */
	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {

	}

}
